const axios = require("axios");

function getTenantAccessToken() {
  return new Promise((resolve, reject) => {
    const data = JSON.stringify({
      app_id: "cli_a58ab33f4cb8100e",
      app_secret: "BoHi410nBc1jNfRzVsPnehgtOk8ix6UR",
    });

    axios
      .post(
        "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
        data,
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then((response) => {
        if (response.data.code === 0) {
          resolve(response.data.tenant_access_token);
        } else {
          reject(new Error("Failed to get tenant_access_token"));
        }
      })
        .catch((error) => {
            console.log(error,'getTenantAccessToken')
        reject(error);
      });
  });
}

function sendMessage(receive_id, msg_type, content, token) {
  let data = JSON.stringify({
    receive_id: receive_id,
    msg_type: msg_type,
    content: content,
  });
  let config = {
    method: "POST",
    url: "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    data: data,
  };

  return axios(config)
    .then(function (response) {
      console.log("发送卡片成功");
      return response; // 同样也可以选择返回特定的数据或者整个 response
    })
    .catch(function (error) {
      console.log("发送卡片失败:", error);
      throw error; // 重新抛出错误以便外部的 try...catch 可以捕获它
    });
}
function updateCardDetails(token, data, messageid) {
  let config = {
    method: "PATCH",
    url: "https://open.feishu.cn/open-apis/im/v1/messages/" + messageid,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    data: data,
  };

  console.log(config);

  axios(config) // 直接返回这个 Promise
    .then(function (response) {
      console.log("更新成功");
    })
    .catch(function (error) {
      console.log("更新失败:", error);
      throw error; // 重新抛出这个 error 以便外部的 try...catch 可以捕获它
    });
}
//获取消息内容
function getMessageDetails(token, messageid) {
  let config = {
    method: "GET",
    url: `https://open.feishu.cn/open-apis/im/v1/messages/${messageid}`,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  // 返回Promise
  return axios(config)
    .then(function (response) {
      return response.data.data.items[0].body; // 这个数据会被Promise resolve
    })
    .catch(function (error) {
      console.log(error);
      console.log(error.response ? error.response.data : error);
      throw error; // 抛出错误，让外部的catch可以接收
    });
}
module.exports = {
  sendMessage,
  getTenantAccessToken,
  updateCardDetails,
  getMessageDetails,
};
